package com.itlxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itlxd.common.ThreadLocalUtils;
import com.itlxd.dto.OrderDTO;
import com.itlxd.dto.PageDTO;
import com.itlxd.entity.*;
import com.itlxd.global.SysConstants;
import com.itlxd.mapper.AddressBookMapper;
import com.itlxd.mapper.OrderDetailMapper;
import com.itlxd.mapper.OrdersMapper;
import com.itlxd.mapper.UserMapper;
import com.itlxd.service.IOrdersService;
import com.itlxd.service.IShoppingCartService;
import com.itlxd.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-12-25
 */
@Transactional
@Service
public class OrdersServiceImpl implements IOrdersService {

    @Autowired
    private OrdersMapper orderMapper;
    @Autowired
    private IShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer insertOrder(OrderDTO orderDTO) {
        Orders order = new Orders();
        BeanUtils.copyProperties(orderDTO, order);
        List<OrderDetail> orderDetails = orderDTO.getOrderDetail();

        AddressBook addressBook = addressBookMapper.selectById(orderDTO.getAddressBookId());
        order.setConsignee(addressBook.getConsignee());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());

        User user = userMapper.selectById(orderDTO.getUserId());
        order.setUserName(user.getName());

        BigDecimal amount = new BigDecimal(SysConstants.NUM_ZERO);
        Integer number = new Integer(0);
        //计算总金额 和 数量
        for (OrderDetail orderDetail : orderDetails) {
            amount = orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber())).add(amount);
            number += orderDetail.getNumber();
        }


        //默认状态为2
        order.setStatus(SysConstants.NUM_TWO);
        order.setAmount(amount);
        order.setNumber(number.toString());
        int insertNum = orderMapper.insert(order);

        orderDetails.forEach(item -> {
            item.setOrderId(order.getId());
            orderDetailMapper.insert(item);
        });

        //删除数据库中的购物车信息
        shoppingCartService.deleteShoppingCart(ThreadLocalUtils.getCurrentId());

        return insertNum;
    }


    @Override
    public IPage<OrderVO> listOrderVOByPage(PageDTO pageDTO) {
        IPage<Orders> page = new Page<>(pageDTO.getPage(), pageDTO.getPageSize());
        LambdaQueryWrapper<Orders> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(null != pageDTO.getUserId(), Orders::getUserId, pageDTO.getUserId())
                .eq(null != pageDTO.getId(), Orders::getId, pageDTO.getId())
                .ge(null != pageDTO.getBeginTime(), Orders::getOrderTime, pageDTO.getBeginTime())
                .le(null != pageDTO.getEndTime(), Orders::getOrderTime, pageDTO.getEndTime())
                .orderByDesc(Orders::getOrderTime);
        orderMapper.selectPage(page, lambdaQuery);

        if (null == page.getRecords() && page.getRecords().size() == SysConstants.NUM_ZERO) {
            return null;
        }

        IPage<OrderVO> result = new Page<>();
        List<OrderVO> orderVOList = page.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            LambdaQueryWrapper<OrderDetail> query = new LambdaQueryWrapper();
            query.eq(OrderDetail::getOrderId, order.getId()).orderByDesc(OrderDetail::getName);
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(query);
            orderVO.setOrderDetails(orderDetails);
            return orderVO;
        }).collect(Collectors.toList());

        result.setRecords(orderVOList);
        result.setTotal(page.getTotal());
        return result;
    }

    @Override
    public Integer updateOrder(Orders order) {
        return orderMapper.updateById(order);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer insertOrderAgain(Long id) {
        //清空购物车
        shoppingCartService.deleteShoppingCart(ThreadLocalUtils.getCurrentId());

        Orders order = orderMapper.selectById(id);
        LambdaQueryWrapper<OrderDetail> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(OrderDetail::getOrderId, order.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(lambdaQuery);

        int count = 0;
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //因为订单详情id会拷贝到购物车当中，所以设置购物车id为null，通过雪花算法自动生成id
            shoppingCart.setId(null);
            shoppingCart.setUserId(ThreadLocalUtils.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            count += shoppingCartService.insertShoppingCart(shoppingCart);
        }

        return count;
    }
}
